package com.derbysoft.dswitch.adapter.ihg.web.action.admin.setting.rateplan;

import com.derbysoft.dswitch.adapter.ihg.common.domain.RatePlan;
import com.derbysoft.dswitch.adapter.ihg.common.repository.RatePlanRepository;
import com.derbysoft.dswitch.adapter.ihg.web.action.support.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

public class AddAction extends BaseAction {
    @Autowired
    private RatePlanRepository ratePlanRepository;

    private RatePlan ratePlan;

    private static final String ERROR_DESC = "error_desc";

    @Action("add")
    public String execute() {
        if (ratePlanRepository.loadByCode(ratePlan.getCode()) != null) {
            ((HttpServletRequest) ActionContext.getContext()
                    .get(ServletActionContext.HTTP_REQUEST)).setAttribute(ERROR_DESC, ratePlan.getCode() + " : had already exists !!");
            return view();
        }
        ratePlanRepository.save(ratePlan);
        return LIST;
    }

    public String view() {
        return VIEW;
    }

    public RatePlan getRatePlan() {
        return ratePlan;
    }

    public void setRatePlan(RatePlan ratePlan) {
        this.ratePlan = ratePlan;
    }
}